<template>
  <div class="app-container">
    <div class="menu-layout">
      <!-- 右侧主内容区 -->
      <div class="menu-main">
        <!-- 顶部搜索和操作按钮 -->
        <div class="main-header">
          <div class="search-bar">
            <el-input
              v-model="selFunctionListQuery.name"
              placeholder="请输入菜单名称"
              clearable
              style="width: 250px"
            />
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="handleQuery"
            >查询</el-button>
          </div>
          <div class="button-group">
            <el-button
              type="success"
              icon="el-icon-plus"
              @click="handleAdd"
            >新增</el-button>
            <!-- <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
              >批量删除</el-button
            > -->
          </div>
        </div>

        <!-- 表格区域 - 使用直接从API返回的树形数据 -->
        <el-table
          v-loading="listLoading"
          :data="menuList"
          element-loading-text="加载中"
          border
          fit
          row-key="id"
          :tree-props="{ children: 'list', hasChildren: 'hasChildren' }"
          highlight-current-row
          style="height: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="(row) => row.name !== '首页'"
          />

          <el-table-column
            label="菜单名称"
            prop="name"
            align="center"
            min-width="200"
          >
            <template slot-scope="scope">
              <span
                :style="
                  !scope.row.parentId
                    ? 'font-weight: bold; color: #409EFF;'
                    : ''
                "
              >
                {{ scope.row.name }}
              </span>
              <el-tag
                v-if="!scope.row.parentId"
                size="mini"
                type="primary"
                style="margin-left: 8px"
              >父菜单</el-tag>
              <el-tag
                v-else
                size="mini"
                type="info"
                style="margin-left: 8px"
              >子菜单</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="菜单地址"
            prop="url"
            align="center"
            min-width="150"
          />

          <!-- <el-table-column label="层级排序" align="center" min-width="150">
            <template slot-scope="scope">
              <span>{{ formatMenuPath(scope.row) }}</span>
            </template>
          </el-table-column> -->

          <el-table-column
            align="center"
            prop="createTime"
            label="创建时间"
            min-width="150"
          >
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="是否显示" width="100" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
                :disabled="hasChildren(scope.row) || scope.row.name === '首页'"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                :disabled="scope.row.name === '首页'"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="mini"
                :disabled="scope.row.name === '首页'"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page.sync="selFunctionListQuery.page"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="selFunctionListQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增对话框 -->
    <el-dialog
      title="新增菜单"
      :visible.sync="dialogVisible"
      width="500px"
      @close="close"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入菜单名称"
          />
        </el-form-item>
        <el-form-item label="菜单地址" prop="url">
          <el-input
            v-model="formData.url"
            placeholder="请输入菜单地址"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="formData.isShow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可关闭">
          <el-radio-group v-model="formData.isClose">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑菜单"
      :visible.sync="editDialogVisible"
      width="500px"
      @close="close"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input
            v-model="editFormData.name"
            placeholder="请输入菜单名称"
          />
        </el-form-item>
        <el-form-item label="菜单地址" prop="url">
          <el-input
            v-model="editFormData.url"
            placeholder="请输入菜单地址"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="editFormData.isShow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可关闭">
          <el-radio-group v-model="editFormData.isClose">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selMenuListApi,
  selMenuByIdApi,
  addMenuApi,
  updateMenuByIdApi,
  delMenuByIdsApi,
  downMenuByIdApi
} from '@/api/system'

export default {
  name: 'MenuManagement',
  data() {
    return {
      listLoading: false,
      // 菜单查询参数
      selFunctionListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      // 总条数
      total: 0,
      // 菜单数据 - 直接使用API返回的数据
      menuList: [],
      // 选中的行
      selectedRows: [],
      selectedIds: [],
      // 对话框显示
      dialogVisible: false,
      editDialogVisible: false,
      // 新增表单数据
      formData: {
        isClose: 1,
        isShow: 1,
        name: '',
        url: '',
        parentId: null
      },
      // 编辑表单数据
      editFormData: {
        id: '',
        isClose: 1,
        isShow: 1,
        name: '',
        url: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { max: 50, message: '菜单名称不能超过50个字符', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入菜单地址', trigger: 'blur' },
          { max: 100, message: '菜单地址不能超过100个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMenuData()
  },
  methods: {
    // 获取菜单数据
    async getMenuData() {
      this.listLoading = true
      try {
        const res = await selMenuListApi(this.selFunctionListQuery)
        if (res && res.records) {
          // 直接使用API返回的数据，它已经包含了正确的嵌套结构
          this.menuList = res.records
          this.total = res.total || 0
          console.log('菜单数据:', this.menuList) // 调试输出
        } else {
          this.$message.warning('获取菜单列表数据格式不正确')
        }
      } catch (error) {
        console.error('获取菜单列表失败:', error)
        this.$message.error('获取菜单列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 格式化菜单路径
    formatMenuPath(row) {
      if (!row.parentId) {
        return row.id || ''
      } else {
        return `${row.parentId} > ${row.id}`
      }
    },

    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      return time.substring(0, 16)
    },

    // 查询
    handleQuery() {
      this.selFunctionListQuery.page = 1
      this.getMenuData()
    },

    // 重置查询
    resetQuery() {
      this.selFunctionListQuery = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.getMenuData()
    },

    // 处理新增
    handleAdd() {
      this.formData = {
        isClose: 1,
        isShow: 1,
        name: '',
        url: '',
        parentId: null
      }

      if (this.selectedRows.length === 1) {
        this.formData.parentId = this.selectedRows[0].id
      } else if (this.selectedRows.length > 1) {
        this.$message.warning('只能选择一个菜单作为父菜单')
        return
      }

      this.dialogVisible = true
    },

    // 处理编辑
    handleEdit(row) {
      this.editFormData = {
        id: row.id,
        name: row.name,
        url: row.url,
        isShow: row.isShow,
        isClose: row.isClose
      }
      this.editDialogVisible = true
    },

    // 处理删除
    handleDelete(row) {
      if (row.list && row.list.length > 0) {
        return this.$message.warning('该菜单下存在子菜单，请先删除子菜单')
      }

      this.$confirm(`确定要删除菜单"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delMenuByIdsApi([row.id])
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.getMenuData()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除菜单失败:', error)
            this.$message.error('删除菜单失败')
          }
        })
        .catch(() => {})
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      // 过滤掉首页菜单
      this.selectedRows = selection.filter((item) => item.name !== '首页')
      this.selectedIds = this.selectedRows.map((item) => item.id)
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        return this.$message.warning('请至少选择一个菜单')
      }

      this.$confirm(
        `确定要删除选中的${this.selectedIds.length}个菜单吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          try {
            const res = await delMenuByIdsApi(this.selectedIds)
            if (res.code === 1) {
              this.$message.success('批量删除成功')
              this.getMenuData()
            } else {
              this.$message.error(res.msg || '批量删除失败')
            }
          } catch (error) {
            console.error('批量删除菜单失败:', error)
            this.$message.error('批量删除菜单失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    // 判断是否有子菜单
    hasChildren(row) {
      return row.list && row.list.length > 0
    },

    // 处理菜单状态变化
    async handleStatusChange(row) {
      // 如果是父菜单，不允许改变状态
      if (this.hasChildren(row)) {
        this.$message.warning('父菜单状态不可直接修改，请修改其子菜单')
        return
      }

      try {
        const res = await downMenuByIdApi(row.id)
        if (res.code === 1) {
          this.$message.success(`菜单"${row.name}"状态修改成功`)
          this.getMenuData()
        } else {
          row.isShow = row.isShow === 1 ? 2 : 1 // 恢复原状态
          this.$message.error(res.msg || '状态修改失败')
        }
      } catch (error) {
        row.isShow = row.isShow === 1 ? 2 : 1 // 恢复原状态
        console.error('修改菜单状态失败:', error)
        this.$message.error('修改菜单状态失败')
      }
    },

    // 关闭对话框
    close() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.resetFields()
      }
    },

    // 提交新增
    async handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (!valid) return

        try {
          const submitData = {
            isClose: this.formData.isClose,
            isShow: this.formData.isShow,
            name: this.formData.name,
            url: this.formData.url,
            parentId: this.formData.parentId || null
          }

          const res = await addMenuApi(submitData)
          if (res.code === 1) {
            this.$message.success('新增菜单成功')
            this.dialogVisible = false
            this.getMenuData()
          } else {
            this.$message.error(res.msg || '新增菜单失败')
          }
        } catch (error) {
          console.error('新增菜单出错:', error)
          this.$message.error('新增菜单失败，请稍后重试')
        }
      })
    },

    // 提交编辑
    async handleEditSubmit() {
      this.$refs.editFormRef.validate(async(valid) => {
        if (!valid) return

        try {
          const res = await updateMenuByIdApi({
            id: this.editFormData.id,
            name: this.editFormData.name,
            url: this.editFormData.url,
            isShow: this.editFormData.isShow,
            isClose: this.editFormData.isClose
          })

          if (res.code === 1) {
            this.$message.success('编辑菜单成功')
            this.editDialogVisible = false
            this.getMenuData()
          } else {
            this.$message.error(res.msg || '编辑菜单失败')
          }
        } catch (error) {
          console.error('编辑菜单出错:', error)
          this.$message.error('编辑菜单失败，请稍后重试')
        }
      })
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.selFunctionListQuery.pageSize = val
      this.getMenuData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.selFunctionListQuery.page = val
      this.getMenuData()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 顶层容器占据整个视口高度减去头部高度 */
.app-container {
  padding: 20px;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

/* 菜单布局占据app-container的全部可用高度 */
.menu-layout {
  flex: 1;
  display: flex;
  border: 1px solid #ebeef5;
  overflow: hidden;
  height: 100%; /* 关键：明确设置高度 */
}

/* 主内容区占据menu-layout的全部可用高度 */
.menu-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
  overflow: hidden;
  height: 100%; /* 关键：明确设置高度 */
  box-sizing: border-box;
}

/* 头部固定高度不压缩 */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

/* ======== 表格样式强化 ======== */
/* 表格容器占据除了header和pagination之外的全部空间 */
::v-deep .el-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100% !important; /* 强制设置高度 */
  min-height: 0;
}

/* 表头不压缩 */
::v-deep .el-table__header-wrapper {
  flex-shrink: 0;
}

/* 表格主体区域占据所有剩余空间 */
::v-deep .el-table__body-wrapper {
  flex: 1;
  overflow-y: auto !important;
  height: auto !important;
  min-height: 0 !important; /* 允许压缩 */
  max-height: none !important; /* 不限制最大高度 */
}

/* 分页区域固定高度不压缩 */
.pagination-container {
  margin-top: 15px;
  text-align: right;
  flex-shrink: 0;
}

/* 其他样式保持不变 */
.search-bar {
  display: flex;
  align-items: center;
}

.button-group {
  text-align: right;
}

::v-deep .el-table__expand-icon {
  color: #409eff;
}

/* 调试辅助 - 可删除 */
::v-deep .el-table::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: red;
  z-index: 9999;
}
</style>
